home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Internet Tools 1993 July / Internet Tools.iso / RockRidge / mail / pine / imap-3.0 / non-ANSI / c-client / os_ptx.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-06-07  |  21.9 KB  |  827 lines

  1. /*
  2.  * Program:    Operating-system dependent routines -- PTX version
  3.  *
  4.  * Author:    Donn Cave/Mark Crispin
  5.  *        University Computing Services, JE-30
  6.  *        University of Washington
  7.  *        Seattle, WA 98195
  8.  *        Internet: donn@cac.washington.edu
  9.  *
  10.  * Date:    11 May 1989
  11.  * Last Edited:    7 June 1993
  12.  *
  13.  * Copyright 1993 by the University of Washington
  14.  *
  15.  *  Permission to use, copy, modify, and distribute this software and its
  16.  * documentation for any purpose and without fee is hereby granted, provided
  17.  * that the above copyright notice appears in all copies and that both the
  18.  * above copyright notice and this permission notice appear in supporting
  19.  * documentation, and that the name of the University of Washington not be
  20.  * used in advertising or publicity pertaining to distribution of the software
  21.  * without specific, written prior permission.  This software is made
  22.  * available "as is", and
  23.  * THE UNIVERSITY OF WASHINGTON DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED,
  24.  * WITH REGARD TO THIS SOFTWARE, INCLUDING WITHOUT LIMITATION ALL IMPLIED
  25.  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND IN
  26.  * NO EVENT SHALL THE UNIVERSITY OF WASHINGTON BE LIABLE FOR ANY SPECIAL,
  27.  * INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  28.  * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, TORT
  29.  * (INCLUDING NEGLIGENCE) OR STRICT LIABILITY, ARISING OUT OF OR IN CONNECTION
  30.  * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  31.  *
  32.  */
  33.  
  34. /* TCP input buffer */
  35.  
  36. #define BUFLEN 8192
  37.  
  38.  
  39. /* TCP I/O stream (must be before osdep.h is included) */
  40.  
  41. #define TCPSTREAM struct tcp_stream
  42. TCPSTREAM {
  43.   char *host;            /* host name */
  44.   char *localhost;        /* local host name */
  45.   int tcpsi;            /* input socket */
  46.   int tcpso;            /* output socket */
  47.   int ictr;            /* input counter */
  48.   char *iptr;            /* input pointer */
  49.   char ibuf[BUFLEN];        /* input buffer */
  50. };
  51.  
  52.  
  53. #include "osdep.h"
  54. #include <ctype.h>
  55. #include <sys/time.h>
  56. #include <sys/tiuser.h>
  57. #include <sys/stropts.h>
  58. #include <sys/poll.h>
  59. #include <netinet/in.h>
  60. #include <netdb.h>
  61. #include <ctype.h>
  62. #include <regexpr.h>
  63. #include <errno.h>
  64. #include <pwd.h>
  65. #include <shadow.h>
  66. #include <syslog.h>
  67. #include <sys/file.h>
  68. #include <sys/stat.h>
  69. #include "mail.h"
  70. #include "misc.h"
  71.  
  72. extern int sys_nerr;
  73. extern char *sys_errlist[];
  74.  
  75. #define toint(c)    ((c)-'0')
  76. #define isodigit(c)    (((unsigned)(c)>=060)&((unsigned)(c)<=067))
  77.  
  78. /* Write current time in RFC 822 format
  79.  * Accepts: destination string
  80.  */
  81.  
  82. char *days[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
  83.  
  84. void rfc822_date (date)
  85.     char *date;
  86. {
  87.   int zone,dstnow;
  88.   struct tm *t;
  89.   time_t time_sec = time (0);
  90.   t = localtime (&time_sec);    /* convert to individual items */
  91.   tzset ();            /* initialize timezone/daylight variables */
  92.                 /* see if it is DST now */
  93.   dstnow = daylight && t->tm_isdst;
  94.                 /* get timezone value */
  95.   zone = - (dstnow ? altzone : timezone) / 60;
  96.                 /* and output it */
  97.   sprintf (date,"%s, %d %s %d %02d:%02d:%02d %+03d%02d (%s)",
  98.        days[t->tm_wday],t->tm_mday,months[t->tm_mon],t->tm_year+1900,
  99.        t->tm_hour,t->tm_min,t->tm_sec,zone/60,abs (zone) % 60,
  100.        tzname[dstnow]);
  101. }
  102.  
  103. /* Get a block of free storage
  104.  * Accepts: size of desired block
  105.  * Returns: free storage block
  106.  */
  107.  
  108. void *fs_get (size)
  109.     size_t size;
  110. {
  111.   void *block = malloc (size);
  112.   if (!block) fatal ("Out of free storage");
  113.   return (block);
  114. }
  115.  
  116.  
  117. /* Resize a block of free storage
  118.  * Accepts: ** pointer to current block
  119.  *        new size
  120.  */
  121.  
  122. void fs_resize (block,size)
  123.     void **block;
  124.     size_t size;
  125. {
  126.   if (!(*block = realloc (*block,size))) fatal ("Can't resize free storage");
  127. }
  128.  
  129.  
  130. /* Return a block of free storage
  131.  * Accepts: ** pointer to free storage block
  132.  */
  133.  
  134. void fs_give (block)
  135.     void **block;
  136. {
  137.   free (*block);
  138.   *block = NIL;
  139. }
  140.  
  141.  
  142. /* Report a fatal error
  143.  * Accepts: string to output
  144.  */
  145.  
  146. void fatal (string)
  147.     char *string;
  148. {
  149.   mm_fatal (string);        /* output the string */
  150.   syslog (LOG_ALERT,"IMAP C-Client crash: %s",string);
  151.   abort ();            /* die horribly */
  152. }
  153.  
  154. /* Copy string with CRLF newlines
  155.  * Accepts: destination string
  156.  *        pointer to size of destination string
  157.  *        source string
  158.  *        length of source string
  159.  */
  160.  
  161. char *strcrlfcpy (dst,dstl,src,srcl)
  162.     char **dst;
  163.     unsigned long *dstl;
  164.     char *src;
  165.     unsigned long srcl;
  166. {
  167.   long i,j;
  168.   char *d = src;
  169.                 /* count number of LF's in source string(s) */
  170.   for (i = srcl,j = 0; j < srcl; j++) if (*d++ == '\012') i++;
  171.   if (i > *dstl) {        /* resize if not enough space */
  172.     fs_give ((void **) dst);    /* fs_resize does an unnecessary copy */
  173.     *dst = (char *) fs_get ((*dstl = i) + 1);
  174.   }
  175.   d = *dst;            /* destination string */
  176.                 /* copy strings, inserting CR's before LF's */
  177.   while (srcl--) switch (*src) {
  178.   case '\015':            /* unlikely carriage return */
  179.     *d++ = *src++;        /* copy it and any succeeding linefeed */
  180.     if (srcl && *src == '\012') {
  181.       *d++ = *src++;
  182.       srcl--;
  183.     }
  184.     break;
  185.   case '\012':            /* line feed? */
  186.     *d++ ='\015';        /* yes, prepend a CR, drop into default case */
  187.   default:            /* ordinary chararacter */
  188.     *d++ = *src++;        /* just copy character */
  189.     break;
  190.   }
  191.   *d = '\0';            /* tie off destination */
  192.   return *dst;            /* return destination */
  193. }
  194.  
  195.  
  196. /* Length of string after strcrlfcpy applied
  197.  * Accepts: source string
  198.  *        length of source string
  199.  */
  200.  
  201. unsigned long strcrlflen (s)
  202.     STRING *s;
  203. {
  204.   unsigned long pos = GETPOS (s);
  205.   unsigned long i = SIZE (s);
  206.   unsigned long j = i;
  207.   while (j--) switch (SNX (s)) {/* search for newlines */
  208.   case '\015':            /* unlikely carriage return */
  209.     if (j && (CHR (s) == '\012')) {
  210.       SNX (s);            /* eat the line feed */
  211.       j--;
  212.     }
  213.     break;
  214.   case '\012':            /* line feed? */
  215.     i++;
  216.   default:            /* ordinary chararacter */
  217.     break;
  218.   }
  219.   SETPOS (s,pos);        /* restore old position */
  220.   return i;
  221. }
  222.  
  223. /* Server log in
  224.  * Accepts: user name string
  225.  *        password string
  226.  *        optional place to return home directory
  227.  * Returns: T if password validated, NIL otherwise
  228.  */
  229.  
  230. long server_login (user,pass,home,argc,argv)
  231.     char *user;
  232.     char *pass;
  233.     char **home;
  234.     int argc;
  235.     char *argv[];
  236. {
  237.   struct passwd *pw = getpwnam (lcase (user));
  238.   struct spwd *sp;
  239.                 /* no entry for this user or root */
  240.   if (!(pw && pw->pw_uid)) return NIL;
  241.                 /* validate password and password aging */
  242.   sp = getspnam (pw->pw_name);
  243.   if (strcmp (sp->sp_pwdp, (char *) crypt (pass,sp->sp_pwdp))) return NIL;
  244.   else if ((sp->sp_lstchg > 0) && (sp->sp_max > 0) &&
  245.        ((sp->sp_lstchg + sp->sp_max) < (time (0) / (60*60*24))))
  246.     return NIL;
  247.   setgid (pw->pw_gid);        /* all OK, login in as that user */
  248.   initgroups (user);        /* initialize groups */
  249.   setuid (pw->pw_uid);
  250.                 /* note home directory */
  251.   if (home) *home = cpystr (pw->pw_dir);
  252.   return T;
  253. }
  254.  
  255. /* Return my user name
  256.  * Returns: my user name
  257.  */
  258.  
  259. char *uname = NIL;
  260.  
  261. char *myusername ()
  262. {
  263.   return uname ? uname : (uname = cpystr (getpwuid (geteuid ())->pw_name));
  264. }
  265.  
  266.  
  267. /* Return my home directory name
  268.  * Returns: my home directory name
  269.  */
  270.  
  271. char *hdname = NIL;
  272.  
  273. char *myhomedir ()
  274. {
  275.   return hdname ? hdname : (hdname = cpystr (getpwuid (geteuid ())->pw_dir));
  276. }
  277.  
  278.  
  279. /* Build status lock file name
  280.  * Accepts: scratch buffer
  281.  *        file name
  282.  * Returns: name of file to lock
  283.  */
  284.  
  285. char *lockname (tmp,fname)
  286.     char *tmp;
  287.     char *fname;
  288. {
  289.   int i;
  290.   sprintf (tmp,"/tmp/.%s",fname);
  291.   for (i = 6; i < strlen (tmp); ++i) if (tmp[i] == '/') tmp[i] = '\\';
  292.   return tmp;            /* note name for later */
  293. }
  294.  
  295. /* TCP/IP open
  296.  * Accepts: host name
  297.  *        contact port number
  298.  * Returns: TCP/IP stream if success else NIL
  299.  */
  300.  
  301. TCPSTREAM *tcp_open (host,port)
  302.     char *host;
  303.     int port;
  304. {
  305.   TCPSTREAM *stream = NIL;
  306.   int sock;
  307.   char *s;
  308.   struct sockaddr_in sin;
  309.   struct hostent *host_name;
  310.   char hostname[MAILTMPLEN];
  311.   char tmp[MAILTMPLEN];
  312.     extern int t_errno;
  313.     extern char *t_errlist[];
  314.     struct t_call *sndcall;
  315.  
  316.   /* The domain literal form is used (rather than simply the dotted decimal
  317.      as with other Unix programs) because it has to be a valid "host name"
  318.      in mailsystem terminology. */
  319.                 /* look like domain literal? */
  320.   if (host[0] == '[' && host[(strlen (host))-1] == ']') {
  321.     strcpy (hostname,host+1);    /* yes, copy number part */
  322.     hostname[(strlen (hostname))-1] = '\0';
  323.     if ((sin.sin_addr.s_addr = inet_addr (hostname)) != -1) {
  324.       sin.sin_family = AF_INET;    /* family is always Internet */
  325.       strcpy (hostname,host);    /* hostname is user's argument */
  326.     }
  327.     else {
  328.       sprintf (tmp,"Bad format domain-literal: %.80s",host);
  329.       mm_log (tmp,ERROR);
  330.       return NIL;
  331.     }
  332.   }
  333.  
  334.   else {            /* lookup host name, note that brain-dead Unix
  335.                    requires lowercase! */
  336.     strcpy (hostname,host);    /* in case host is in write-protected memory */
  337.     if ((host_name = gethostbyname (lcase (hostname)))) {
  338.                 /* copy address type */
  339.       sin.sin_family = host_name->h_addrtype;
  340.                 /* copy host name */
  341.       strcpy (hostname,host_name->h_name);
  342.                 /* copy host addresses */
  343.       memcpy (&sin.sin_addr,host_name->h_addr,host_name->h_length);
  344.     }
  345.     else {
  346.       sprintf (tmp,"No such host as %.80s",host);
  347.       mm_log (tmp,ERROR);
  348.       return NIL;
  349.     }
  350.   }
  351.  
  352.                 /* copy port number in network format */
  353.   if (!(sin.sin_port = htons (port))) fatal ("Bad port argument to tcp_open");
  354.  
  355.                 /* get a TCP stream */
  356.   t_errno = 0;
  357.   if (((sock = t_open (TLI_TCP, O_RDWR, 0)) < 0) ||
  358.       (t_bind (sock, 0, 0) < 0) ||
  359.       ((sndcall = (struct t_call *) t_alloc (sock, T_CALL, T_ADDR)) == 0))
  360.   {
  361.     sprintf (tmp,"Unable to create TCP socket: %s",t_errlist[t_errno]);
  362.     mm_log (tmp,ERROR);
  363.     return NIL;
  364.   }
  365.                 /* connect to address. */
  366.   sndcall->addr.len = sndcall->addr.maxlen = sizeof (sin);
  367.   sndcall->addr.buf = (char *) &sin;
  368.   sndcall->opt.len = 0;
  369.   sndcall->udata.len = 0;
  370.   if (t_connect (sock, sndcall, 0) < 0) {
  371.     sprintf (tmp,"Can't connect to %.80s,%d: %s",hostname,port,
  372.          t_errlist[t_errno]);
  373.     mm_log (tmp,ERROR);
  374.     return NIL;
  375.   }
  376.                 /* push streams module for read()/write(). */
  377.   if (ioctl (sock, I_PUSH, "tirdwr") < 0) {
  378.     sprintf (tmp,"Unable to create TCP socket: %s",t_errlist[t_errno]);
  379.     mm_log (tmp,ERROR);
  380.     return NIL;
  381.   }
  382.                 /* create TCP/IP stream */
  383.   stream = (TCPSTREAM *) fs_get (sizeof (TCPSTREAM));
  384.                 /* copy official host name */
  385.   stream->host = cpystr (hostname);
  386.                 /* get local name */
  387.   gethostname (tmp,MAILTMPLEN-1);
  388.   stream->localhost = cpystr ((host_name = gethostbyname (tmp)) ?
  389.                   host_name->h_name : tmp);
  390.                 /* init sockets */
  391.   stream->tcpsi = stream->tcpso = sock;
  392.   stream->ictr = 0;        /* init input counter */
  393.   return stream;        /* return success */
  394. }
  395.  
  396. /* TCP/IP authenticated open
  397.  * Accepts: host name
  398.  *        service name
  399.  * Returns: TCP/IP stream if success else NIL
  400.  */
  401.  
  402. TCPSTREAM *tcp_aopen (host,service)
  403.     char *host;
  404.     char *service;
  405. {
  406.   TCPSTREAM *stream = NIL;
  407.   struct hostent *host_name;
  408.   char hostname[MAILTMPLEN];
  409.   int i;
  410.   int pipei[2],pipeo[2];
  411.   /* The domain literal form is used (rather than simply the dotted decimal
  412.      as with other Unix programs) because it has to be a valid "host name"
  413.      in mailsystem terminology. */
  414.                 /* look like domain literal? */
  415.   if (host[0] == '[' && host[i = (strlen (host))-1] == ']') {
  416.     strcpy (hostname,host+1);    /* yes, copy without brackets */
  417.     hostname[i-1] = '\0';
  418.   }
  419.                 /* note that Unix requires lowercase! */
  420.   else if (host_name = gethostbyname (lcase (strcpy (hostname,host))))
  421.     strcpy (hostname,host_name->h_name);
  422.                 /* make command pipes */
  423.   if (pipe (pipei) < 0) return NIL;
  424.   if (pipe (pipeo) < 0) {
  425.     close (pipei[0]); close (pipei[1]);
  426.     return NIL;
  427.   }
  428.   if ((i = fork ()) < 0) {    /* make inferior process */
  429.     close (pipei[0]); close (pipei[1]);
  430.     close (pipeo[0]); close (pipeo[1]);
  431.     return NIL;
  432.   }
  433.   if (i) {            /* parent? */
  434.     close (pipei[1]);        /* close child's side of the pipes */
  435.     close (pipeo[0]);
  436.   }
  437.   else {            /* child */
  438.     dup2 (pipei[1],1);        /* parent's input is my output */
  439.     dup2 (pipei[1],2);        /* parent's input is my error output too */
  440.     close (pipei[0]); close (pipei[1]);
  441.     dup2 (pipeo[0],0);        /* parent's output is my input */
  442.     close (pipeo[0]); close (pipeo[1]);
  443.                 /* now run it */
  444.     execl ("/usr/ucb/resh","resh",hostname,"exec",service,0);
  445.     _exit (1);            /* spazzed */
  446.   }
  447.  
  448.                 /* create TCP/IP stream */
  449.   stream = (TCPSTREAM *) fs_get (sizeof (TCPSTREAM));
  450.                 /* copy official host name */
  451.   stream->host = cpystr (hostname);
  452.                 /* get local name */
  453.   gethostname (hostname,MAILTMPLEN-1);
  454.   stream->localhost = cpystr ((host_name = gethostbyname (hostname)) ?
  455.                   host_name->h_name : hostname);
  456.   stream->tcpsi = pipei[0];    /* init sockets */
  457.   stream->tcpso = pipeo[1];
  458.   stream->ictr = 0;        /* init input counter */
  459.   return stream;        /* return success */
  460. }
  461.  
  462. /* TCP/IP receive line
  463.  * Accepts: TCP/IP stream
  464.  * Returns: text line string or NIL if failure
  465.  */
  466.  
  467. char *tcp_getline (stream)
  468.     TCPSTREAM *stream;
  469. {
  470.   int n,m;
  471.   char *st,*ret,*stp;
  472.   char c = '\0';
  473.   char d;
  474.                 /* make sure have data */
  475.   if (!tcp_getdata (stream)) return NIL;
  476.   st = stream->iptr;        /* save start of string */
  477.   n = 0;            /* init string count */
  478.   while (stream->ictr--) {    /* look for end of line */
  479.     d = *stream->iptr++;    /* slurp another character */
  480.     if ((c == '\015') && (d == '\012')) {
  481.       ret = (char *) fs_get (n--);
  482.       memcpy (ret,st,n);    /* copy into a free storage string */
  483.       ret[n] = '\0';        /* tie off string with null */
  484.       return ret;
  485.     }
  486.     n++;            /* count another character searched */
  487.     c = d;            /* remember previous character */
  488.   }
  489.                 /* copy partial string from buffer */
  490.   memcpy ((ret = stp = (char *) fs_get (n)),st,n);
  491.                 /* get more data from the net */
  492.   if (!tcp_getdata (stream)) return NIL;
  493.                 /* special case of newline broken by buffer */
  494.   if ((c == '\015') && (*stream->iptr == '\012')) {
  495.     stream->iptr++;        /* eat the line feed */
  496.     stream->ictr--;
  497.     ret[n - 1] = '\0';        /* tie off string with null */
  498.   }
  499.                 /* else recurse to get remainder */
  500.   else if (st = tcp_getline (stream)) {
  501.     ret = (char *) fs_get (n + 1 + (m = strlen (st)));
  502.     memcpy (ret,stp,n);        /* copy first part */
  503.     memcpy (ret + n,st,m);    /* and second part */
  504.     fs_give ((void **) &stp);    /* flush first part */
  505.     fs_give ((void **) &st);    /* flush second part */
  506.     ret[n + m] = '\0';        /* tie off string with null */
  507.   }
  508.   return ret;
  509. }
  510.  
  511. /* TCP/IP receive buffer
  512.  * Accepts: TCP/IP stream
  513.  *        size in bytes
  514.  *        buffer to read into
  515.  * Returns: T if success, NIL otherwise
  516.  */
  517.  
  518. long tcp_getbuffer (stream,size,buffer)
  519.     TCPSTREAM *stream;
  520.     unsigned long size;
  521.     char *buffer;
  522. {
  523.   unsigned long n;
  524.   char *bufptr = buffer;
  525.   while (size > 0) {        /* until request satisfied */
  526.     if (!tcp_getdata (stream)) return NIL;
  527.     n = min (size,stream->ictr);/* number of bytes to transfer */
  528.                 /* do the copy */
  529.     memcpy (bufptr,stream->iptr,n);
  530.     bufptr += n;        /* update pointer */
  531.     stream->iptr +=n;
  532.     size -= n;            /* update # of bytes to do */
  533.     stream->ictr -=n;
  534.   }
  535.   bufptr[0] = '\0';        /* tie off string */
  536.   return T;
  537. }
  538.  
  539.  
  540. /* TCP/IP receive data
  541.  * Accepts: TCP/IP stream
  542.  * Returns: T if success, NIL otherwise
  543.  */
  544.  
  545. long tcp_getdata (stream)
  546.     TCPSTREAM *stream;
  547. {
  548.   struct pollfd pollfd;
  549.   int pollstatus;
  550.   if (stream->tcpsi < 0) return NIL;
  551.   pollfd.fd = stream->tcpsi;    /* initialize selection vector */
  552.   while (stream->ictr < 1) {    /* if nothing in the buffer */
  553.     pollfd.events = POLLIN;    /* block and read */
  554.     /* Note: am not sure here that it wouldn't also be a good idea to
  555.     restart poll() on EINTR, if SIGCHLD or whatever are expected.    DC */
  556.     while (((pollstatus = poll (&pollfd,1,-1)) < 0) && (errno == EAGAIN));
  557.     if (!pollstatus ||
  558.     ((stream->ictr = read (stream->tcpsi,stream->ibuf,BUFLEN)) < 1)) {
  559.       close (stream->tcpsi);    /* nuke the socket */
  560.       if (stream->tcpsi != stream->tcpso) close (stream->tcpso);
  561.       stream->tcpsi = stream->tcpso = -1;
  562.       return NIL;
  563.     }
  564.     stream->iptr = stream->ibuf;/* point at TCP buffer */
  565.   }
  566.   return T;
  567. }
  568.  
  569. /* TCP/IP send string as record
  570.  * Accepts: TCP/IP stream
  571.  *        string pointer
  572.  * Returns: T if success else NIL
  573.  */
  574.  
  575. long tcp_soutr (stream,string)
  576.     TCPSTREAM *stream;
  577.     char *string;
  578. {
  579.   return tcp_sout (stream,string,(unsigned long) strlen (string));
  580. }
  581.  
  582.  
  583. /* TCP/IP send string
  584.  * Accepts: TCP/IP stream
  585.  *        string pointer
  586.  *        byte count
  587.  * Returns: T if success else NIL
  588.  */
  589.  
  590. long tcp_sout (stream,string,size)
  591.     TCPSTREAM *stream;
  592.     char *string;
  593.     unsigned long size;
  594. {
  595.   int i;
  596.   struct pollfd pollfd;
  597.   int pollstatus;
  598.   pollfd.fd = stream->tcpso;    /* initialize selection vector */
  599.   pollfd.events = POLLOUT;
  600.   if (stream->tcpso < 0) return NIL;
  601.   while (size > 0) {        /* until request satisfied */
  602.     while (((pollstatus = poll (&pollfd,1,-1)) < 0) && (errno == EAGAIN));
  603.     if (!pollstatus ||
  604.     ((i = write (stream->tcpso,string,size)) < 0)) {
  605.       puts (strerror (errno));
  606.       close (stream->tcpsi);    /* nuke the socket */
  607.       if (stream->tcpsi != stream->tcpso) close (stream->tcpso);
  608.       stream->tcpsi = stream->tcpso = -1;
  609.       return NIL;
  610.     }
  611.     size -= i;            /* count this size */
  612.     string += i;
  613.   }
  614.   return T;            /* all done */
  615. }
  616.  
  617. /* TCP/IP close
  618.  * Accepts: TCP/IP stream
  619.  */
  620.  
  621. void tcp_close (stream)
  622.     TCPSTREAM *stream;
  623. {
  624.  
  625.   if (stream->tcpsi >= 0) {    /* no-op if no socket */
  626.     close (stream->tcpsi);    /* nuke the socket */
  627.     if (stream->tcpsi != stream->tcpso) close (stream->tcpso);
  628.     stream->tcpsi = stream->tcpso = -1;
  629.   }
  630.                 /* flush host names */
  631.   fs_give ((void **) &stream->host);
  632.   fs_give ((void **) &stream->localhost);
  633.   fs_give ((void **) &stream);    /* flush the stream */
  634. }
  635.  
  636.  
  637. /* TCP/IP get host name
  638.  * Accepts: TCP/IP stream
  639.  * Returns: host name for this stream
  640.  */
  641.  
  642. char *tcp_host (stream)
  643.     TCPSTREAM *stream;
  644. {
  645.   return stream->host;        /* return host name */
  646. }
  647.  
  648.  
  649. /* TCP/IP get local host name
  650.  * Accepts: TCP/IP stream
  651.  * Returns: local host name
  652.  */
  653.  
  654. char *tcp_localhost (stream)
  655.     TCPSTREAM *stream;
  656. {
  657.   return stream->localhost;    /* return local host name */
  658. }
  659.  
  660. /* Emulator for BSD gethostid() call
  661.  * Returns: unique identifier for this machine
  662.  */
  663.  
  664. long gethostid ()
  665. {
  666.   struct sockaddr_in sin;
  667.   int inet = t_open (TLI_TCP, O_RDWR, 0);
  668.   if (inet < 0) return 0;
  669.   getmyinaddr (inet,&sin,sizeof (sin));
  670.   close (inet);
  671.   return sin.sin_addr.s_addr;
  672. }
  673.  
  674.  
  675. /* Emulator for BSD random() call
  676.  * Returns: long random number
  677.  */
  678.  
  679. long random ()
  680. {
  681.   static int beenhere = 0;
  682.   if (!beenhere) {
  683.     beenhere = 1;
  684.     srand48 (getpid ());
  685.   }
  686.   return lrand48 ();
  687. }
  688.  
  689.  
  690. /* Copy memory block
  691.  * Accepts: destination pointer
  692.  *        source pointer
  693.  *        length
  694.  * Returns: destination pointer
  695.  */
  696.  
  697. void *memmove (s,ct,n)
  698.     void *s;
  699.     void *ct;
  700.     int n;
  701. {
  702.   char *dp, *sp;
  703.   int i;
  704.   unsigned long dest = (unsigned long) s;
  705.   unsigned long src = (unsigned long) ct;
  706.   if (((dest < src) && ((dest + n) < src)) ||
  707.       ((dest > src) && ((src + n) < dest))) return memcpy (s, ct, n);
  708.   dp = s;
  709.   sp = ct;
  710.   if (dest < src) for (i = 0; i < n; ++i) dp[i] = sp[i];
  711.   else if (dest > src) for (i = n - 1; i >= 0; --i) dp[i] = sp[i];
  712.   return s;
  713. }
  714.  
  715. /* Emulator for BSD scandir() call
  716.  * Accepts: directory name
  717.  *        destination pointer of names array
  718.  *        selection function
  719.  *        comparison function
  720.  * Returns: number of elements in the array or -1 if error
  721.  */
  722.  
  723. #define DIRSIZ(d) d->d_reclen
  724.  
  725. int scandir (dirname,namelist,select,compar)
  726.     char *dirname;
  727.     struct dirent ***namelist;
  728.     int (*select) ();
  729.     int (*compar) ();
  730. {
  731.   struct dirent *p,*d,**names;
  732.   int nitems;
  733.   struct stat stb;
  734.   long nlmax;
  735.   DIR *dirp = opendir (dirname);/* open directory and get status poop */
  736.   if ((!dirp) || (fstat (dirp->dd_fd,&stb) < 0)) return -1;
  737.   nlmax = stb.st_size / 24;    /* guesstimate at number of files */
  738.   names = (struct dirent **) fs_get (nlmax * sizeof (struct dirent *));
  739.   nitems = 0;            /* initially none found */
  740.   while (d = readdir (dirp)) {    /* read directory item */
  741.                 /* matches select criterion? */
  742.     if (select && !(*select) (d)) continue;
  743.                 /* get size of dirent record for this file */
  744.     p = (struct dirent *) fs_get (DIRSIZ (d));
  745.     p->d_ino = d->d_ino;    /* copy the poop */
  746.     p->d_off = d->d_off;
  747.     p->d_reclen = d->d_reclen;
  748.     strcpy (p->d_name,d->d_name);
  749.     if (++nitems >= nlmax) {    /* if out of space, try bigger guesstimate */
  750.       nlmax *= 2;        /* double it */
  751.       fs_resize ((void **) names,nlmax * sizeof (struct dirent *));
  752.     }
  753.     names[nitems - 1] = p;    /* store this file there */
  754.   }
  755.   closedir (dirp);        /* done with directory */
  756.                 /* sort if necessary */
  757.   if (nitems && compar) qsort (names,nitems,sizeof (struct dirent *),compar);
  758.   *namelist = names;        /* return directory */
  759.   return nitems;        /* and size */
  760. }
  761.  
  762. /* Emulator for BSD flock() call
  763.  * Accepts: file descriptor
  764.  *        operation bitmask
  765.  * Returns: 0 if successful, -1 if failure
  766.  * Note: this emulator does not handle shared locks
  767.  */
  768.  
  769. int flock (fd, operation)
  770.     int fd;
  771.     int operation;
  772. {
  773.   int func;
  774.   off_t offset = lseek (fd,0,L_INCR);
  775.   switch (operation & ~LOCK_NB){/* translate to lockf() operation */
  776.   case LOCK_EX:            /* exclusive */
  777.   case LOCK_SH:            /* shared */
  778.     func = (operation & LOCK_NB) ? F_TLOCK : F_LOCK;
  779.     break;
  780.   case LOCK_UN:            /* unlock */
  781.     func = F_ULOCK;
  782.     break;
  783.   default:            /* default */
  784.     errno = EINVAL;
  785.     return -1;
  786.   }
  787.   lseek (fd,0,L_SET);        /* position to start of the file */
  788.   func = lockf (fd,func,0);    /* do the lockf() */
  789.   lseek (fd,offset,L_SET);    /* restore prior position */
  790.   return func;
  791. }
  792.  
  793.  
  794. /* Emulator for BSD gettimeofday() call
  795.  * Accepts: address where to write timeval information
  796.  *        address where to write timezone information
  797.  * Returns: 0 if successful, -1 if failure
  798.  */
  799.  
  800. int gettimeofday (tp,tzp)
  801.     struct timeval *tp;
  802.     struct timezone *tzp;
  803. {
  804.   tp->tv_sec = time (0);    /* time since 1-Jan-70 00:00:00 GMT in secs */
  805.                 /* others aren't used in current code */
  806.   if (tzp) tzp->tz_minuteswest = tzp->tz_dsttime = 0;
  807.   tp->tv_usec = 0;
  808.   return 0;
  809. }
  810.  
  811.  
  812. /* Emulator for BSD utimes() call
  813.  * Accepts: file name
  814.  *        timeval vector for access and updated time
  815.  * Returns: 0 if successful, -1 if failure
  816.  */
  817.  
  818. int utimes (file,tvp)
  819.     char *file;
  820.     struct timeval tvp[2];
  821. {
  822.   struct utimbuf tb;
  823.   tb.actime = tvp[0].tv_sec;    /* accessed time */
  824.   tb.modtime = tvp[1].tv_sec;    /* updated time */
  825.   return utime (file,&tb);
  826. }
  827.